<?php
class StatSinglePeriodPrintAction extends CAction {
	public function run() {
		$statModel = new AccountTokenSinglePeriodPrint();
		$statModel->unsetAttributes(); // clear any default values
		if (isset($_GET['AccountTokenSinglePeriodPrint'])) {
			$statModel->attributes = $_GET['AccountTokenSinglePeriodPrint'];
			if ($statModel->validate()) {
				$itemModel = AccountTokenItem::model();
				$commandBuilder = Yii::app()->db->getSchema()->getCommandBuilder();
				$criteriaBase = $statModel->createCriteria();
				$criteriaBase->join = 'INNER JOIN {{account_token}} as token on tokenId=token.id INNER JOIN {{account_token_category}} as category on categoryId=category.id';

				$categories = $this->findFirstLevelCategories();
				foreach ($categories as $category) {
					$criteria = new CDbCriteria();
					$criteria->mergeWith($criteriaBase);
					$criteria
						->addInCondition('category.id',
							CMap::mergeArray(preg_split('/[\|]+/', $category->childrenCache),
								array(
									$category->id
								)));
					$criteria->select = 'sum(debit) as totalDebit, sum(credit) as totalCredit';
					$command = $commandBuilder
						->createFindCommand($itemModel->getTableSchema(), $criteria);
					$row = $command->queryRow();
					if ($row['totalDebit'] == 0 && $row['totalCredit'] == 0) {
						continue;
					}
					$item = new AccountTokenSinglePeriodPrintItem;
					$item->category = $category;
					$item->credit = $row['totalCredit'];
					$item->debit = $row['totalDebit'];
					$statModel->items[] = $item;
				}

				$criteriaBase->select = 'sum(debit) as totalDebit, sum(credit) as totalCredit';

				$command = $commandBuilder
					->createFindCommand($itemModel->getTableSchema(), $criteriaBase);
				$row = $command->queryRow();
				$statModel->totalCredit = $row['totalCredit'];
				$statModel->totalDebit = $row['totalDebit'];
				$statModel->createUser = AccessControl::getCurrentUser();
			}
		}

		$this->getController()
			->render('statSinglePeriodPrint',
				array(
					'statModel' => $statModel,
				//'overallStat' => $overallStat,
				));
	}

	private function findFirstLevelCategories() {
		return AccountTokenCategory::model()
			->findAll(
				array(
					'with' => 'parent',
					'condition' => 't.parentId IS NOT NULL AND parent.parentId IS NULL'
				));
	}
}
